package business;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.ArrayList;
import java.util.ListIterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import orm.Users;

import dao.UserDAO;
import util.Utility;
import util.DBHelper;

public class UserServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public UserServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int PageSize = Utility.PageSize;
		String strFunc = request.getParameter("func");
		
		if (strFunc == null) {
			return;
		} else if (strFunc.equals("load")) {

			request.getRequestDispatcher("../" + Utility.JSP_UserAdd).forward(request, response);
		} else if (strFunc.endsWith("save")) {
//			int userID = Integer.parseInt(request.getParameter("UserID"));
			String userName = request.getParameter("UserName").toString();
			UserDAO userDAO = new UserDAO();
			try {
				if (userDAO.doesUserExist(userName)) {
					request.setAttribute("flag", "flag");
					request.getRequestDispatcher("../" + Utility.JSP_UserAdd).forward(request, response);
					return;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			Users user = new Users();

			pickupFormData(user, request);
			user.setRoleID(2);
			insertData(user);
			
			try {
				request.setAttribute("pageNo", 1);
				ArrayList<Users> al = userDAO.getAllUsers();
				if (al.size() % PageSize == 0) {
					request.setAttribute("totalPage",al.size()/PageSize);
				} else {
					request.setAttribute("totalPage",(al.size()/PageSize) + 1);
				}
				
				al = new ArrayList<Users>();
				ListIterator<Users> it = userDAO.getAllUsers().listIterator();
				int ii = 0;
				while (it.hasNext()) {
					Users t = it.next();
					Users t1 = new Users();
						
					t1.setUserID(t.getUserID());
					t1.setRealName(t.getRealName());
					t1.setPosition(t.getPosition());
					t1.setAuthorizationDate(t.getAuthorizationDate());
					
					al.add(t1);
					ii++;
					if(ii > (PageSize-1) ) {
						break;
					}
					
				}
				
				request.setAttribute("userList", al);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			request.getRequestDispatcher("../" + Utility.JSP_UserInfo).forward(request, response);

		}else if (strFunc.equals("edit")) {
			Users user = new Users();
			
//			String teacherID = request.getAttribute("teacherID").toString();
			int userID = Integer.parseInt(request.getParameter("UserID"));		
			pickupFormData(user, request);
			user.setRoleID(2);
			
			updateData(user, userID);
			UserDAO userDAO = new UserDAO();

			try {
				request.setAttribute("pageNo", 1);
				ArrayList<Users> al = userDAO.getAllUsers();
				if (al.size() % PageSize == 0) {
					request.setAttribute("totalPage",al.size()/PageSize);
				} else {
					request.setAttribute("totalPage",(al.size()/PageSize) + 1);
				}
				
				al = new ArrayList<Users>();
				ListIterator<Users> it = userDAO.getAllUsers().listIterator();
				int ii = 0;
				while (it.hasNext()) {
					Users t = it.next();
					Users t1 = new Users();
						
					t1.setUserID(t.getUserID());
					t1.setRealName(t.getRealName());
					t1.setPosition(t.getPosition());
					t1.setAuthorizationDate(t.getAuthorizationDate());
					
					al.add(t1);
					ii++;
					if(ii > (PageSize-1) ) {
						break;
					}
					
				}
				
				request.setAttribute("userList", al);
			} catch (SQLException e) {
				e.printStackTrace();
			}

			request.getRequestDispatcher("../" + Utility.JSP_UserInfo).forward(request, response);
		} 
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	public void pickupFormData(Users user, HttpServletRequest request) {
		user.setRealName(request.getParameter("RealName"));
		user.setPosition(request.getParameter("Position"));

		String strDateTmp = request.getParameter("txtBirthdayYear");
		user.setAuthorizationDate(strDateTmp);
		
		user.setUserName(request.getParameter("UserName"));
		user.setPwd(request.getParameter("Pwd"));

	}
	
	public void updateData(Users user,  int userID) {
		Connection conn = DBHelper.getConnection();
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			conn.setAutoCommit(false);
			
			UserDAO userDAO = new UserDAO();
			user.setUserID(userID);
			userDAO.updateUser(stmt, user);

			conn.commit();
			
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException ee) {
				
			}
		}
	}

	public void insertData(Users user) {
		try {
			UserDAO userDAO = new UserDAO();
			userDAO.insertUser(user);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
